﻿using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Routing.Matching;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using WMSSystem.DYB;
using WMSSystem.YJ.DTO.Input;
using WMSSystem.YJ.DTO.Out;
using WMSSystem.YJ.Interface;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WMSSystem.YJ
{
    public class TransferTableAppService : ApplicationService, ITransferTableAppService
    {
        private readonly IRepository<Transfertable, Guid> _transfertableRepository;
        private readonly IRepository<InventoryGoods, Guid> _inventoryGoodsRepository;
        private readonly IRepository<Commoditiestable, Guid> _commoditiestableRepository;
        private readonly IRepository<WarehouseManagement,Guid> _warehouseManagementRepository;

        public TransferTableAppService(IRepository<Transfertable, Guid> transfertableRepository, IRepository<InventoryGoods, Guid> inventoryGoodsRepository, IRepository<Commoditiestable, Guid> commoditiestableRepository, IRepository<WarehouseManagement, Guid> warehouseManagementRepository)
        {
            _transfertableRepository = transfertableRepository;
            _inventoryGoodsRepository = inventoryGoodsRepository;
            _commoditiestableRepository = commoditiestableRepository;
            _warehouseManagementRepository = warehouseManagementRepository;
        }
        /// <summary>
        /// 创建调拨单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagingTransferTableOut> CreateCommodities(CreateTransferTableDTO input)
        {
            input.HomeId = input.TransferInhome;
            var ids = "";
            foreach (var item in input.InvenoryGoodData)
            {
                ids = ids + item.CommoditiesId + ",";
            }
            input.CommoditiesId = ids.Substring(0,ids.Length - 1);           

           var data=ObjectMapper.Map<CreateTransferTableDTO, Transfertable>(input);
            ///完成商品调拨表添加
          var res2=  await _transfertableRepository.InsertAsync(data);
            ///修改的库存信息
            var InventioryGoods = ObjectMapper.Map<List<InventoryGoodsDTO>, List<InventoryGoods>>(input.InvenoryGoodData);
            ///获取所有库存
            //var GoodsAll = await _inventoryGoodsRepository.GetListAsync(x => x.PositionManagementId.ToString() == input.TransferInhome);
            var i = 0;

            foreach (var item in InventioryGoods)
            {
                //int trannum = 0;
                //if (item.CommoditiesId != null && item.PositionManagementId != null)
                //{
                //    var GoodsUpdate = await _inventoryGoodsRepository.GetListAsync(x => x.CommoditiesId == item.CommoditiesId && x.PositionManagementId == item.PositionManagementId);
                //    foreach (var item1 in GoodsUpdate)
                //    { 
                //        item1.TransferNumber= item1.TransferNumber-item.TransferNumber;
                //        trannum = (int)item1.TransferNumber!;
                //        await _inventoryGoodsRepository.UpdateAsync(item1);
                //    }
                //}
                var positoionid = Guid.Parse(input.TransferInhome);
                //item.TransferNumber= trannum;
                item.PositionManagementId = positoionid;
                item.TransfertableId = data.Id;
                var res = await _inventoryGoodsRepository.InsertAsync(item);
                if (res != null)
                {
                    i = i + 1;
                }
                else
                {
                    i = i + 0;
                }
            }
            if (i == InventioryGoods.Count && res2 != null)
            {
                return ObjectMapper.Map<Transfertable, PagingTransferTableOut>(data);
            }
            else
            {
                return new PagingTransferTableOut() { };
            }              
        }
        /// <summary>
        /// 删除调拨单
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeleteCommodities(string Ids)
        {
            string[] data = Ids.Split(",");
            var number = 0;
            foreach (var item in data)
            {
                var data1 = await _transfertableRepository.GetAsync(x => x.Id.ToString() == item);
                if (data1 == null)
                {
                    throw new Exception("数据不存在");
                }
                var list = _transfertableRepository.DeleteAsync(data1);
                if (list != null)
                {
                    number = number + 1;
                }
                else
                {
                    number = number + 0;
                }

            }
            if (number == data.Count())
            {
                return 200;
            }
            else
            {
                return 500;
            }
        }
        /// <summary>
        /// 获取调拨单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PagingTransferTableOut>> GetCommoditiesTable(PagingTransferTableDTO input)
        {          
            var query = await _transfertableRepository.GetQueryableAsync();           
            if (!string.IsNullOrWhiteSpace(input.TransferCode))
            { 
                query= query.Where(x => x.TransferCode.Equals(input.TransferCode));
            }
            if (!string.IsNullOrWhiteSpace(input.Usernmae))
            {
                query = query.Where(x => x.Usernmae.Equals(input.Usernmae));
            }
            if (!string.IsNullOrWhiteSpace(input.TransferType))
            {
                query = query.Where(x => x.TransferType.Equals(input.TransferType));
            }
            if (!string.IsNullOrWhiteSpace(input.CommoditiesId))
            {
                query = query.Where(x => x.CommoditiesId.Equals(input.CommoditiesId));
            }
            var totalCount = query.Count();
            var ss = query.ToList();
            var query2 = ObjectMapper.Map<List<Transfertable>, List<PagingTransferTableOut>>(ss);
            foreach (var sid in query2)
            {
                if (sid.CommoditiesId != null&&sid.CommoditiesId!="string"&&sid.CommoditiesId!="")
                {
                    string[] comids = sid.CommoditiesId.Split(",");
                    string comname = "";
                    foreach (var item in comids)
                    {
                        try
                        {
                            if (Guid.TryParse(item, out Guid guid))
                            {
                                var comdata = await _commoditiestableRepository.GetAsync(guid);
                                if (comdata != null)
                                {
                                    comname = comname + comdata.CommoditiesName;
                                }
                            }
                        }
                        catch (EntityNotFoundException)
                        {
                            // 记录日志或跳过不存在的商品
                            continue;
                        }
                    }
                    sid.CommoditiesId = comname;
                }

                if (!string.IsNullOrEmpty(sid.TransferOuthome))
                {
                    try
                    {
                        if (Guid.TryParse(sid.TransferOuthome, out Guid outHomeGuid))
                        {
                            var wardata1 = await _warehouseManagementRepository.GetAsync(outHomeGuid);
                            if (wardata1 != null)
                            {
                                sid.TransferOuthome = wardata1.Name;
                                
                            }
                        }
                    }
                    catch (EntityNotFoundException)
                    {
                        // 记录日志或设置默认值
                        sid.TransferOuthome = "未知仓库";
                    }
                }

                // 处理调入仓库
                if (!string.IsNullOrEmpty(sid.TransferInhome))
                {
                    try
                    {
                        if (Guid.TryParse(sid.TransferInhome, out Guid inHomeGuid))
                        {
                            var wardata2 = await _warehouseManagementRepository.GetAsync(inHomeGuid);
                            if (wardata2 != null)
                            {
                                sid.TransferInhome = wardata2.Name;
                                sid.HomeId = wardata2.Name;
                            }
                        }
                    }
                    catch (EntityNotFoundException)
                    {
                        // 记录日志或设置默认值
                        sid.TransferInhome = "未知仓库";
                    }
                }
            }  
            var items = query2.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            return new PagedResultDto<PagingTransferTableOut>(
                 totalCount,                                 
                query2
             );
        }
        /// <summary>
        /// 获取调拨单-一条数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<PagingTransferTableOut> GetValue(Guid Id)
        {
            var data = await _transfertableRepository.GetAsync(Id);           
            var GoodData = await _inventoryGoodsRepository.GetListAsync(x => x.TransfertableId == Id);
            var list = ObjectMapper.Map<Transfertable, PagingTransferTableOut>(data);
            var ceshi = ObjectMapper.Map<List<InventoryGoods>, List<InventoryGoodsDTO>>(GoodData);
            foreach (var item in ceshi)
            {
                if (item.CommoditiesId != null)
                {
                    var comdata =await _commoditiestableRepository.GetAsync(item.CommoditiesId);
                    if (comdata != null)
                    {
                        item.CommoditiesName = comdata.CommoditiesName;
                    }                   
                }               
            }

            list.InvenoryGoodData = ceshi;
            return list;
        }
        /// <summary>
        /// 修改调拨单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagingTransferTableOut> UpdateCommodities(UpdateTransferTableDTO input)
        {
            var data = await _transfertableRepository.GetAsync(x => x.Id.ToString() == input.Id);

            var ids = "";
            foreach (var item in input.InvenoryGoodData)
            {
                ids = ids + item.CommoditiesId + ",";
            }
            data.CommoditiesId = ids.Substring(0, ids.Length - 1);

            data.HomeId = input.HomeId;
            ObjectMapper.Map(input, data);
            await _transfertableRepository.UpdateAsync(data);

            var i = 0;
            foreach (var item in input.InvenoryGoodData)
            {
                var ss =await _inventoryGoodsRepository.GetListAsync(x => x.TransfertableId == item.Id);
                if (ss != null)
                {
                    foreach (var s in ss)
                    {
                        await _inventoryGoodsRepository.DeleteAsync(s.Id);
                    }
                }
               
            }

            foreach (var item in input.InvenoryGoodData)
            {
                string guidString = input.Id;
                Guid? guid = null;

                 if (Guid.TryParse(guidString, out Guid result))
                {
                    guid = result;
                }
                var positoionid = Guid.Parse(input.TransferInhome);
                item.PositionManagementId = positoionid;
                var newGood = new InventoryGoods
                {
                    CommoditiesId = item.CommoditiesId,
                    Inventory = item.Inventory,
                    Unit = item.Unit,
                    Specs = item.Specs,
                    CommoditiesType = item.CommoditiesType,
                    TransferNumber = item.TransferNumber,
                    InMoney = item.InMoney,
                    TransferTableMoney = item.TransferTableMoney,
                    Desc = item.Desc,
                    PositionManagementId = Guid.Parse(input.TransferInhome), 
                    TransfertableId = guid
                };

                await _inventoryGoodsRepository.InsertAsync(newGood);
            }
           
            return ObjectMapper.Map<Transfertable, PagingTransferTableOut>(data);
        }
    }
}
